﻿using MPic.Business.Entity;
using MPic.Business.Models.QiNiu;
using MPic.Utility;
using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MPic.Common
{
    /// <summary>
    /// 七牛上传帮助类
    /// </summary>
    public static class QiNiuUploadHelper
    {
        public static string Upload(QiNiuEntity qiniu, string fileName, string filePath)
        {
            string imgUrl = string.Empty;
            try
            {
                // 生成(上传)凭证时需要使用此Mac
                // 这个示例单独使用了一个Settings类，其中包含AccessKey和SecretKey
                // 实际应用中，请自行设置您的AccessKey和SecretKey
                Mac mac = new Mac(qiniu.AccessKey, qiniu.SecretKey);
                string localFile = filePath;
                // 上传策略，参见 
                // https://developer.qiniu.com/kodo/manual/put-policy
                PutPolicy putPolicy = new PutPolicy();
                // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
                // putPolicy.Scope = bucket + ":" + saveKey;
                putPolicy.Scope = qiniu.Bucket;
                // 上传策略有效期(对应于生成的凭证的有效期)          
                putPolicy.SetExpires(3600);
                // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
                putPolicy.DeleteAfterDays = 1;
                // 生成上传凭证，参见
                // https://developer.qiniu.com/kodo/manual/upload-token            
                string jstr = putPolicy.ToJsonString();
                string token = Auth.CreateUploadToken(mac, jstr);
                UploadManager um = new UploadManager();
                HttpResult result = um.UploadFile(localFile, fileName, token);
                if (result.Code.Equals(200))
                {
                    var uploadReuslt = JsonConvert.DeserializeObject<QiNiu_UploadResult>(result.Text);
                    imgUrl = uploadReuslt.key;
                }
            }
            catch (Exception e)
            {
                LoggerHelper.Log($"【七牛上传】出错，错误原因：{e.Message}");
            }
            return imgUrl;
        }
    }
}